﻿using Authentication.Core.Configuration;
using Authentication.Core.Data;
using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract.Authentication.Record;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Data.Repository.Enum;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Globalization;
using System.Linq;

namespace Authentication.Provider
{
    public class CloseDaoProvider : GenericProvider, ICloseDaoProvider
    {
        public List<CloseDaoRequest> RetrieveListCloseDaoRequest(out int totalRecord, UserRecord currentUser, FilterRecord textSearch = null, int pagesize = 0, int pageindex = 0, SortRecord sortRecord = null)
        {
            int curIdGroup = int.Parse(currentUser.GroupIdentifier);
            var data = repository.DbContext as AuthenticationEntities;
            var query = from x in data.CloseDaoRequests.Include(x => x.Branch)
                        select x;
            if (currentUser.GroupIdentifier.Equals("6") || currentUser.GroupIdentifier.Equals("4"))
            {
                query = query.Where(x => x.Pic.Equals(currentUser.UserName));
            }
            if (SystemConfiguration.UserMBDApprovedDao.Contains(currentUser.UserName))
            {
                query = query.Where(x => x.Branch.Region.Contains("MBD"));
            }
            if (textSearch.CreateDaoRequestStatus.HasValue)
            {
                query = query.Where(x => x.Status == textSearch.CreateDaoRequestStatus);
            }
            else
            {
                query = query.Where(x => string.IsNullOrEmpty(x.RejectPerson) || x.GroupIdReject.Value <= curIdGroup);
            }
            if (textSearch.IsExport == true)
            {
                query = query.Where(x => x.Status == (int)StatusCloseDaoEnum.BranchApproved || x.Status == (int)StatusCloseDaoEnum.RegionApproved);
            }
            if (SystemConfiguration.UserBICApprovedDao.Contains(currentUser.UserName))
            {
                query = query.Where(x => x.Status != (int)StatusCloseDaoEnum.Request);
            }

            if (!string.IsNullOrEmpty(textSearch.Region) && textSearch.Region.Trim() != "null")
            {
                query = query.Where(x => textSearch.Region.ToUpper().Contains(x.Branch.Region.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.Branch) && textSearch.Branch.Trim() != "null")
            {
                query = query.Where(x => textSearch.Branch.ToUpper().Contains(x.Branch.BranchId.ToUpper()));
            }
            if (!string.IsNullOrEmpty(textSearch.RequestId))
            {
                query = query.Where(x => ("CD" + x.Id.ToString()).Contains(textSearch.RequestId));
            }
            if (!string.IsNullOrEmpty(textSearch.RequestStatus) && textSearch.RequestStatus != "-1")
            {
                int requestStatus = int.Parse(textSearch.RequestStatus);
                switch (requestStatus)
                {
                    case 9:
                        query = query.Where(x => x.Status == (int)StatusCloseDaoEnum.Reject && x.GroupIdReject == 3);
                        break;
                    case 10:
                        query = query.Where(x => x.Status == (int)StatusCloseDaoEnum.Reject && x.GroupIdReject == 2);
                        break;
                    case 11:
                        query = query.Where(x => x.Status == (int)StatusCloseDaoEnum.Reject && SystemConfiguration.UserBICApprovedDao.Contains(x.RejectPerson));
                        break;
                    case 12:
                        query = query.Where(x => x.Status == (int)StatusCloseDaoEnum.Reject && x.Pic.Equals(x.RejectPerson));
                        break;
                    default:
                        query = query.Where(x => x.Status == requestStatus);
                        break;
                }
            }
            DateTime ToDateCompare = DateTime.Now.AddMonths(1);
            DateTime FromDateCompare = DateTime.Now;
            if (!string.IsNullOrEmpty(textSearch.CusOpenDate))
            {
                List<string> listFilter = textSearch.CusOpenDate.Split('-').ToList();
                FromDateCompare = DateTime.ParseExact(listFilter.FirstOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                ToDateCompare = DateTime.ParseExact(listFilter.LastOrDefault().Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                query = query.Where(x => x.CreatedDate >= FromDateCompare && x.CreatedDate <= ToDateCompare);
            }
            totalRecord = query.Count();
            bool isAsc = true;
            if (sortRecord != null && sortRecord.SortDir.Count > 0)
            {
                isAsc = sortRecord.SortDir.FirstOrDefault().Equals("asc");

            }
            if (isAsc)
            {
                query = query.OrderBy(x => x.Id);
            }
            else
            {
                query = query.OrderByDescending(x => x.Id);
            }
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }

            return query.ToList();
        }
        public bool SaveCloseDaoRequest(out List<string> listDaoExist, List<CloseDaoRequest> userQuestion)
        {
            listDaoExist = new List<string>();
            try
            {
                var listDao = userQuestion.Select(x => x.Dao).ToList();
                listDaoExist = repository.Find<CloseDaoRequest>(x => listDao.Contains(x.Dao) && (x.Status == (int)StatusCloseDaoEnum.Done || x.Status == (int)StatusCloseDaoEnum.SendEmail)).Select(x => x.Dao).ToList();
                userQuestion.ForEach(x =>
                {
                    var checkRecord = repository.FindOne<CloseDaoRequest>(y => y.Dao.Equals(x.Dao) && (y.Status == (int)StatusCloseDaoEnum.Done || y.Status == (int)StatusCloseDaoEnum.SendEmail));
                    if (checkRecord == null)
                    {
                        repository.Add<CloseDaoRequest>(x);
                    }
                });
                repository.UnitOfWork.SaveChanges();
            }
            catch
            {
                return false;
            }
            return true;
        }
        public bool UpdateStatusCloseDaoRequest(CloseDaoRequest checkUser)
        {
            var checkRecord = repository.FindOne<CloseDaoRequest>(x => x.Id == checkUser.Id);
            if (checkRecord == null)
            {
                return false;
            }
            else
            {
                if (checkRecord.Status == (int)StatusCloseDaoEnum.Reject)
                {
                    checkRecord.GroupIdReject = checkUser.GroupIdReject;
                    checkRecord.RejectPerson = checkUser.RejectPerson;
                }
                checkRecord.Status = checkUser.Status;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
        }
        public bool UpdateStatusListCloseDaoRequest(int[] listId, int status)
        {
            var listCheckRecord = repository.Find<CloseDaoRequest>(x => listId.Contains(x.Id)).ToList();
            if (listCheckRecord != null && listCheckRecord.Count() > 0)
            {
                listCheckRecord.ForEach(x =>
                {
                    x.Status = status;
                });
            }
            repository.UnitOfWork.SaveChanges();
            return true;
        }
        public bool UpdateOfferLetter(CloseDaoRequest checkUser)
        {
            var checkRecord = repository.FindOne<CloseDaoRequest>(x => x.Id == checkUser.Id);
            if (checkRecord == null)
            {
                return false;
            }
            else
            {
                checkRecord.LinkOfferLetter = checkUser.LinkOfferLetter;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
        }
        public CloseDaoRequest RetrieveRequestByRequestId(int id, UserRecord currentUser)
        {
            var data = repository.DbContext as AuthenticationEntities;
            var query = from x in data.CloseDaoRequests.Include(x => x.Branch)
                        where x.Id == id
                        select x;
            if (currentUser.GroupIdentifier.Equals("3"))
            {
                query = query.Where(x => x.BranchCodeSme.Equals(currentUser.BranchCode));
            }
            if (currentUser.UserName.Equals(SystemConfiguration.UserBICApprovedDao))
            {
                query = query.Where(x => x.Status != (int)StatusCloseDaoEnum.Request);
            }
            return query.FirstOrDefault();
        }
    }
}
